var express = require('express')
var router = express.Router()
var db = require('../public/javascripts/db')
var token = require('../public/javascripts/utils')
var config = require('../public/config')
const imgPath = require('../public/javascripts/config').imgPath;

// const imgPath = 'http://localhost/upload/';  //本地环境

function getTime() {
    return new Date().toLocaleString('chinese', {
        hour12: false,
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
    })
}

router.post('/', (req, res, next) => {

    // res.send('put status')
    console.log(req.body);
    console.log(req.body.image.length);

    var sql1 = 'create table if not exists users(' +
        'id int not null auto_increment,' +
        'phone varchar(255),' +
        'name varchar(255),' +
        'identify_num varchar(255),' +
        'gender varchar(255),' +
        'age varchar(255), ' +
        'birth_place varchar(255), ' +
        'birth_date varchar(255), ' +
        'medical_history varchar(255), ' +
        'locked varchar(255), primary key (id))';


    db.query(sql1, (err1, res1) => {
        if (err1) {
            throw err1;
            return;
        } else {
            var add_sql1 = "INSERT INTO `users`" +
                "(phone,name,identify_num,gender,age,birth_place,birth_date,medical_history,locked) " +
                "VALUES (?,?,?,?,?,?,?,?,?) ";
            var add_params1 = [req.body.telephone, req.body.name, req.body.cardNum, req.body.gender,
                req.body.age, req.body.birthPlace, req.body.birthDate, req.body.history, false];
            db.query(add_sql1, add_params1, (err2, res2) => {
                if (err2) {
                    throw err2;
                    return;
                } else {
                    // console.log(res2);
                    var sql2 = 'create table if not exists images(' +
                        'id int not null auto_increment,' +
                        'location varchar(255), ' +
                        'owner_id int, ' +
                        'load_by varchar(255), ' +
                        'load_time varchar(255), ' +
                        'type int, primary key(id))';
                    db.query(sql2, (err3, res3) => {
                        if (err3) {
                            throw err3;
                            return;
                        } else {
                            var add_sql2 = "INSERT INTO `images` (location,owner_id,load_by,load_time,type) VALUES ?";
                            if (req.body.image.length == 2) {
                                var add_params2 = [
                                    [req.body.image[0].src, res2.insertId, token.verifyToken(req.headers.token),
                                        getTime(), req.body.image[0].type],
                                    [req.body.image[1].src, res2.insertId, token.verifyToken(req.headers.token),
                                        getTime(), req.body.image[1].type]
                                ]
                            } else {
                                var add_params2 = [[req.body.image[0].src, res2.insertId, token.verifyToken(req.headers.token),
                                    getTime(), req.body.image[0].type]];
                            }
                            db.query(add_sql2, [add_params2], (err4, res4) => {
                                if (err4) {
                                    throw err4;
                                    return;
                                } else {
                                    console.log('res4', res4);
                                    // for (var i = 0; i < req.body.image.length; i++) {
                                    req.body.image.forEach((index, num) => {
                                        console.log('index', index);
                                        console.log('num', num);
                                        console.log('first i', num);
                                        var exec = require('child_process').exec;
                                        var arg1 = req.body.image[num].src.split('/').pop();
                                        console.log('arg1', arg1)
                                        var filename = config.pythonPath;
                                        // var start = new Date().getTime();
                                        var sql3 = 'create table if not exists tasks (' +
                                            'id int not null auto_increment,' +
                                            'img_id varchar(255),' +
                                            'user_id varchar(255),' +
                                            'owner_id varchar(255),' +
                                            'algorithm varchar(255),' +
                                            'status int,' +
                                            'start_time varchar(255),' +
                                            'end_time varchar(255), primary key (id))';
                                        db.query(sql3, (err5, res5) => {
                                            if (err5) {
                                                throw err5;
                                                return;
                                            } else {
                                                console.log('second i', num);
                                                var add_sql3 = "INSERT INTO `tasks` (img_id,user_id,owner_id,algorithm,status,start_time) VALUES (?,?,?,?,?,?)";
                                                var add_params3 = [
                                                    res4.insertId + num, token.verifyToken(req.headers.token), res2.insertId, 1, 0,
                                                    getTime()
                                                ]
                                                db.query(add_sql3, add_params3, (err6, res6) => {
                                                    if (err6) {
                                                        throw err6;
                                                        return;
                                                    } else {
                                                        exec('python' + ' ' + filename + ' ' + arg1, (err, stdout, stderr) => {
                                                            if (err) {
                                                                console.log('python err', err);
                                                                throw err;
                                                                return;
                                                            } else {
                                                                // var end = new Date().getTime();
                                                                console.log('exec num', num);
                                                                var updateSql = 'UPDATE tasks SET status = ?,end_time = ? WHERE img_id = ?'
                                                                var updateParams = [1, getTime(), res4.insertId + num];
                                                                db.query(updateSql, updateParams, (err7, res7) => {
                                                                    if (err7) {
                                                                        throw err7;
                                                                        return;
                                                                    } else {
                                                                        var sql4 = 'create table if not exists results (' +
                                                                            'id int not null auto_increment,' +
                                                                            'img_id varchar(255),' +
                                                                            'user_id varchar(255),' +
                                                                            'owner_id varchar(255),' +
                                                                            'isDr double,' +
                                                                            'vessel varchar(255),' +
                                                                            'mass_vessel varchar(255), odlocation varchar(255),created_time varchar(255), primary key (id))';
                                                                        db.query(sql4, (err8, res8) => {
                                                                            if (err8) {
                                                                                throw err8;
                                                                                return;
                                                                            } else {
                                                                                console.log('fourth i', num);
                                                                                var add_sql4 = "INSERT INTO `results` (img_id,user_id,owner_id,isDr,vessel,mass_vessel,odlocation,created_time) VALUES (?,?,?,?,?,?,?,?)";
                                                                                var img_name = req.body.image[num].src.split('/').pop().split('.')[0];
                                                                                var add_params4 = [res4.insertId + num, token.verifyToken(req.headers.token), res2.insertId,
                                                                                    1.1, imgPath + img_name + '_vessel.jpg', imgPath + img_name + '_massvessel.jpg',
                                                                                    imgPath + img_name + '_odlocation.jpg', getTime()];
                                                                                db.query(add_sql4, add_params4, (err9, res9) => {
                                                                                    if (err9) {
                                                                                        throw err9;
                                                                                        return;
                                                                                    } else {
                                                                                        if (num == req.body.image.length - 1) {
                                                                                            console.log('done');
                                                                                            res.send({status: 2})
                                                                                        }
                                                                                        // res.send({status: 2})
                                                                                    }
                                                                                })
                                                                            }
                                                                        })
                                                                    }
                                                                })
                                                            }
                                                        })

                                                    }
                                                })
                                            }
                                        })
                                    })

                                    // }


                                    // var exec = require('child_process').exec;
                                    // var arg1 = req.body.data.id + '.jpg';
                                    // var filename = config.pythonPath;
                                    // var start = new Date().getTime();
                                    // exec('python' + ' ' + filename + ' ' + arg1, (err, stdout, stderr) => {
                                    //     if (err) {
                                    //         console.log('stderr:', stderr);
                                    //     } else {
                                    //         var updateSql = 'UPDATE history SET status =?,percent = ? WHERE id = ?';
                                    //         var updateParams = [1, 100, req.body.data.id];
                                    //         db.query(updateSql, updateParams, (err, result) => {
                                    //             if (err) {
                                    //                 console.log('python update', err);
                                    //                 return;
                                    //             }
                                    //             var end = new Date().getTime();
                                    //             console.log('execute time', end - start);
                                    //
                                    //             var sql = 'create table if not exists result(id int,isdr double,masNum double,origin varchar(255),vessel varchar(255),massvessel varchar(255))';
                                    //             db.query(sql, (err, result) => {
                                    //                 if (err) {
                                    //                     throw err;
                                    //                     return;
                                    //                 }
                                    //
                                    //                 //线上环境
                                    //                 // var ftm = stdout.split('\n');
                                    //                 // len = ftm.length;
                                    //                 // var pythonResult = ftm[len - 2];
                                    //                 // console.log('stdout: ', pythonResult);
                                    //                 // var sqlParams = [req.body.data.id, pythonResult[1],pythonResult[0],
                                    //                 //     imgPath + req.body.data.id + '.jpg',
                                    //                 //     imgPath + req.body.data.id + '_vessel.jpg',
                                    //                 //     imgPath + req.body.data.id + '_massvessel.jpg']
                                    //
                                    //                 var addAql = "INSERT INTO `result` (id,isdr,masNum,origin,vessel,massvessel) VALUES(?, ?, ?, ?, ?,?)";
                                    //                 var sqlParams = [req.body.data.id, 1.0, 1.0,
                                    //                     imgPath + req.body.data.id + '.jpg',
                                    //                     imgPath + req.body.data.id + '_vessel.jpg',
                                    //                     imgPath + req.body.data.id + '_massvessel.jpg']
                                    //                 db.query(addAql, sqlParams, (err, result) => {
                                    //                     if (err) {
                                    //                         throw err;
                                    //                         return;
                                    //                     }
                                    //                     console.log('stdout:', stdout);
                                    //                     res.send(stdout);
                                    //                 })
                                    //                 console.log('create result success', result);
                                    //             })
                                    //             // db.query(
                                    //             //     "CREATE TABLE history(" +
                                    //             //     "id int not null auto_increment," +       //数据库自增id
                                    //             //     "userId varchar(255)," +
                                    //             //     "userName varchar(255), " +
                                    //             //     "algorithm varchar(255), " +
                                    //             //     "percent int," +
                                    //             //     "result varchar(255), " +
                                    //             //     "status int, " +
                                    //             //     "time varchar(255),type varchar(255),leftSrc mediumblob,rightSrc mediumblob,primary key (id))", (err, result) => {
                                    //             //         if (err) {
                                    //             //             throw err;
                                    //             //         } else {
                                    //             //             console.log('创建表成功')
                                    //             //         }
                                    //             //     })
                                    //
                                    //             // console.log('python success', result)
                                    //         })
                                    //     }
                                    // })


                                }
                            })
                        }
                    })
                }
            })
        }
    })
})


module.exports = router